__all__ = ['user_crud']

from typing import List
from apps.cruds.crud_base import CRUDBase, ModelType
from apps.models import User
from apps.schemas.user_schema import CreateUserSchema, UpdateUserSchema
from apps.utils import get_password_hash


class CRUDUser(CRUDBase[User, CreateUserSchema, UpdateUserSchema]):
    __doc__ = "用户数据持久层"

    async def rest_password(self, password, **kwargs) -> int:
        return await self.model.filter(**kwargs).update(password=password)

    async def update(self, obj_in: UpdateUserSchema, **kwargs) -> int:
        """
        用户信息更新
        :param obj_in:
        :param kwargs:
        :return:
        """

        obj_in_data = obj_in.dict(skip_defaults=True)
        if obj_in_data.get("password"):
            obj_in_data["password"] = get_password_hash(obj_in_data.get("password"))

        return await self.model.filter(**kwargs).update(**obj_in_data)

    async def get_user_list(self, *, skip=0, limit=10, keyword) -> List[ModelType]:
        """
        查询多条数据 分页
        :param skip:
        :param limit:
        :param kwargs:
        :return:
        """
        return await self.model.filter(account__contains=keyword).offset(skip).limit(limit).order_by("-id").all()

    async def get_user_list_count(self, *, keyword):
        """
        查询多条数据 分页
        :param skip:
        :param limit:
        :param kwargs:
        :return:
        """
        return await self.model.filter(account__contains=keyword).count()


user_crud = CRUDUser(User)
